package com.heima.controller.web.SkuWeb;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.controller.R;
import com.heima.controller.Result;
import com.heima.pojo.Sku;
import com.heima.pojo.SkuClass;
import com.heima.pojo.vo.Sku.SkuDto;
import com.heima.service.SkuClassService;
import com.heima.service.SkuService;
import com.heima.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/vm-service/sku")
public class SkuController {

    @Autowired
    SkuService skuService;

    @Autowired
    SkuClassService skuClassService;

    @Value("${lkd_parent1.path}")
    private String basePath;

    @Autowired
    HttpServletResponse response;

    @Autowired
    HttpServletRequest request;

    //分页查询 返回SkuPageVo
    @GetMapping("/search")
    public Result<List<SkuDto>> findByage(Integer pageIndex, Integer pageSize, String skuName) {
        System.out.println("name = " + skuName);
        log.info("所有的分类分页查询，第{}页，每页{}条", pageIndex, pageSize);
        //健壮性
        if (pageSize == null) {
            pageSize = 10;
        }
        if (pageIndex == null) {
            pageIndex = 1;
        }
        //创建分页对象
        Page<Sku> pageSku = new Page<>(pageIndex, pageSize);
        //创建lam
        LambdaQueryWrapper<Sku> sqw = new LambdaQueryWrapper<>();
        //模糊查询
        sqw.like(skuName != null, Sku::getSkuName, skuName);
        //添加排序规则
        sqw.orderByDesc(Sku::getUpdateTime);
        //进行分页
        skuService.page(pageSku, sqw);

        List<Sku> records = pageSku.getRecords();
        for (Sku record : records) {
            System.out.println("record = " + record);
        }
        //创建分页器对象2
        Page<SkuDto> pageSkuVo = new Page<>(pageIndex, pageSize);
        //进行复制排序规则  去除排序的list
        BeanUtils.copyProperties(pageSku, pageSkuVo, "records");
        //进行填充 先提取
        List<Sku> skus = pageSku.getRecords();
        //使用流进行填充
        List<SkuDto> skuDtos = skus.stream().map((sku) -> {
            SkuDto skuDto = new SkuDto();
            //进行基本的拷贝
            BeanUtils.copyProperties(sku, skuDto);
            //根据sku来获取classId
            Integer classId = sku.getClassId();
            //根据ClassId 来获取SkuClass
            //SkuClass skuClass = skuClassService.getById(classId);
            LambdaQueryWrapper<SkuClass> qw = new LambdaQueryWrapper<>();
            qw.eq(SkuClass::getClassId, classId);
            SkuClass skuClass = skuClassService.getOne(qw);
            //打SkuClass进行填充
            skuDto.setSkuClass(skuClass);
            skuDto.setCapacity(null);
            skuDto.setRealPrice(null);
            //输出成一个list
            return skuDto;
        }).collect(Collectors.toList());
        return Result.success(pageIndex, pageSize, pageSkuVo.getPages(), pageSkuVo.getTotal(), skuDtos);
    }

    //上传
    @PostMapping("/fileUpload")
    public String fileUpload(MultipartFile fileName) throws IOException {
        // 获取原始文件名，获取其真是的后缀（可以不用）
        String ofn = fileName.getOriginalFilename();
        int dotIndex = ofn.lastIndexOf(".");
        String suffixName = ofn.substring(dotIndex);
        /*log.info("后缀名字是={}", suffixName);
        // 包含三级目录的文件名
        String fileNameWithPath = FileUtil.getFileNameWithPath();
        log.info("三级目录的文件名={}", fileNameWithPath);
        // 创建文件
        FileUtil.makeDirs(fileNameWithPath, basePath);
        // 保存到服务硬盘中某个地方（图片运存服务器（对象服务器OSS））
        String s = fileNameWithPath + suffixName;
        File file = new File(basePath + fileNameWithPath + suffixName);
        //进行保存
        request.getSession().setAttribute("myfile", s);
        // BaseContext.setCurrentId(Long.valueOf((basePath + fileNameWithPath + suffixName)));
        //d:/img/xxx.jpg
        // 保存到服务硬盘中某个地方（图片运存服务器（对象服务器OSS））
        fileName.transferTo(file);
//        //给出响应
//        HashMap map = new HashMap();
//        map.put("flag", true); // 将学生信息键值对存储到Map中
//        map.put("name", fileNameWithPath + suffixName);
*/
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        File targetFile = new File(basePath + newFileName + suffixName);
        fileName.transferTo(targetFile);
        System.out.println("newFileName = " + newFileName);

        return "/img/"+newFileName + suffixName;
        //return true;
    }

    //添加
    @PostMapping
    public boolean add(@RequestBody Sku sku) {
        log.info("前台传过来的是{}", sku);

        boolean flag = skuService.add(sku);

        if (flag) {
            return true;
        }
        return false;
    }

    /**
     * 修改
     */
    @PutMapping("/{number}")
    public boolean upDateById(@RequestBody Sku sku, @PathVariable Long number) {

        log.info("number={}", number);
        String myfile = (String) request.getSession().getAttribute("myfile");
        sku.setSkuId(number);
        sku.setSkuImage(myfile);
        boolean update = skuService.updateById(sku);
        return update;
    }


}
